package com.alpaak.common.utils.mqtt;

import com.alpaak.common.adapter.ConfSetPropertyHolder;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;


public class DcMqttServer {

	private final static String HOST = ConfSetPropertyHolder.getProperty("emq_url");
	private final static String USERNAME = ConfSetPropertyHolder.getProperty("emq_user");
	private final static String PASSWORD = ConfSetPropertyHolder.getProperty("emq_password");
	
	
//	public static final String HOST = "tcp://120.26.11.127";
	
//    public static final String TOPIC = "test";  
    private static final String clientid ="server";   
  
    private MqttClient client;  
    private MqttTopic mqttTopic;  
    private String userName = USERNAME;  
    private String passWord = PASSWORD;  
  
    MqttMessage message; 
  
	public DcMqttServer(String topic){  
        //MemoryPersistence设置clientid的保存形式，默认为以内存保存  
        try {
			client = new MqttClient(HOST, clientid, new MemoryPersistence());
			 //连接服务器
	        connect(topic); 
		} catch (MqttException e) {
			e.printStackTrace();
		}
    }  
      
    private void connect(String topic) {
    	// new mqttConnection 用来设置一些连接的属性
        MqttConnectOptions options = new MqttConnectOptions();
        // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接 
        // 换而言之，设置为false时可以客户端可以接受离线消息
        options.setCleanSession(false);
        // 设置连接的用户名和密码
        options.setUserName(userName);  
        options.setPassword(passWord.toCharArray());  
        // 设置超时时间  
        options.setConnectionTimeout(10);  
        // 设置会话心跳时间  
        options.setKeepAliveInterval(20);  
        try {  
        	   // 设置回调类
               client.setCallback(new DcMqttCallback()); 
               // 连接
               client.connect(options);  
               mqttTopic = client.getTopic(topic);  
        } catch (Exception e) {  
               e.printStackTrace();  
        }  
    }  
      
    public void publish(MqttMessage message){ 
    	try {
        	// 发布的方法
        	// new mqttDeliveryToken
        	MqttDeliveryToken token = mqttTopic.publish(message);
        	// 发布
			token.waitForCompletion();
		} catch (MqttException e) {
			e.printStackTrace();
		}   
    }  
}
